package com.lww.feature.test.jmstest;

import javax.jms.*;
import javax.naming.InitialContext;
import java.io.BufferedReader;
import java.io.InputStreamReader;

/**
 * User: yian
 * Date: 2017/9/15
 */
public class Chat implements MessageListener{

    private TopicSession pubSession;

    private TopicPublisher publisher;

    private TopicConnection connection;

    private String userName;

    public Chat(String topicFactory,String topicName, String username) throws Exception{
        InitialContext ctx = new InitialContext();

        TopicConnectionFactory conFactory =
                (TopicConnectionFactory) ctx.lookup(topicFactory);

        TopicConnection connection = conFactory.createTopicConnection();

        TopicSession pubSession
                = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);

        TopicSession subSession
                = connection.createTopicSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic chatTopic = (Topic) ctx.lookup(topicName);
        TopicPublisher publisher = pubSession.createPublisher(chatTopic);
        TopicSubscriber subscriber
                = subSession.createSubscriber(chatTopic, null, true);
        subscriber.setMessageListener(this);
        this.connection = connection;
        this.pubSession = pubSession;
        this.publisher = publisher;
        this.userName = username;

        connection.start();
    }

    @Override
    public void onMessage(Message message) {
        TextMessage textMessage = (TextMessage)message;
        try {
            System.out.println(textMessage.getText());
        } catch (JMSException e) {
            e.printStackTrace();
        }


    }

    protected void writeMessage(String text) throws JMSException {
        TextMessage textMessage
                = pubSession.createTextMessage(userName + " : " + text);
        publisher.publish(textMessage);
    }

    public void close() throws JMSException {
        connection.close();
    }

    public static void main(String[] args) throws Exception {
        if (args.length != 3) {
            System.out.println("params error");

        } else {
            System.out.println(args[0]+args[1]+ args[2]);
            Chat chat = new Chat(args[0], args[1], args[2]);
            BufferedReader commandLine
                    = new BufferedReader(new InputStreamReader(System.in));
            while (true) {
                String s = commandLine.readLine();
                if (s.equals("exit")) {
                    chat.close();
                    System.out.println(s);
                    System.exit(0);
                } else {
                    chat.writeMessage(s);
                }
            }
        }
    }


}
